package com.veo.controller;

import com.veo.dao.DepartmentDao;
import com.veo.dao.EmployeeDao;
import com.veo.entities.Department;
import com.veo.entities.Employee;
import com.veo.exception.UserNotExitException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.Banner;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Collection;
import java.util.Map;

@Controller
public class EmployeeController {

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private DepartmentDao departmentDao;


    @ResponseBody
    @RequestMapping("/hello")
    public String hello(@RequestParam("user")String user){
        if (user.equals("aaa")){
            throw new UserNotExitException();
        }
        return "Hello world";
    }

    @GetMapping("/emps/queryAll")
    public String queryAllEmps(Model model){
        Collection<Employee> all = employeeDao.getAll();
        model.addAttribute("list",all);
        return "emps/list";
    }


    @GetMapping("/toAddPage")
    public String toAddPage(Model model){
        Collection<Department> all = departmentDao.getDepartments();
        model.addAttribute("list",all);
        return "emps/add";
    }
    
    @PostMapping("/emps")
    public String addEmp(Employee employee){
        System.out.println("要添加的员工信息："+employee);
        employeeDao.save(employee);
        return "redirect:/emps/queryAll";
    }

    @GetMapping("/emps/{id}")
    public String addEmp(@PathVariable("id") int id,Model model){
        Employee employee = employeeDao.get(id);
        Collection<Department> all = departmentDao.getDepartments();
        model.addAttribute("list",all);
        model.addAttribute("emp",employee);
        employeeDao.save(employee);
        return "emps/add";
    }

    @PutMapping("/emps")
    public String updateEmp(Employee employee){
        System.out.println("要修改的员工的信息："+employee);
        employeeDao.save(employee);
        return "redirect:/emps/queryAll";
    }


    @DeleteMapping("/emps/{id}")
    public String deleteEmp(@PathVariable("id") int id){
        employeeDao.delete(id);
        return "redirect:/emps/queryAll";
    }


}
